<template>
  <view class="register">
    <view class="head">
      <image src="../../static/images/BackIcon.png" mode="scaleToFill" @click="goBack"/>
    </view>
    <view class="content">
      <view class="title">新用户注册</view>
      <view class="content-item">
        <view class="ipt">
          <text style="color: aliceblue; padding-left: 32rpx">用户名</text>
          <text class="error-tip" v-if="errors.username">{{ errors.username }}</text>
          <input
            type="text"
            placeholder="请输入用户名"
            placeholder-style="color:#666"
            v-model="params.username"
            :maxlength="8"
          />
        </view>
        <view class="ipt">
          <text style="color: aliceblue; padding-left: 32rpx">手机号码</text>
          <text class="error-tip" v-if="errors.phone">{{ errors.phone }}</text>
          <input
            type="number"
            placeholder="请输入手机号"
            placeholder-style="color:#666"
            v-model="params.phone"
            :maxlength="11"
          />
        </view>
        <view class="ipt">
          <text style="color: aliceblue; padding-left: 32rpx">验证码</text>
          <text class="error-tip" v-if="errors.security">{{ errors.security }}</text>
          <view class="security">
            <input
              type="number"
              placeholder="请输入验证码"
              placeholder-style="color:#666"
              v-model="params.security"
              :maxlength="6"
              :minlength="4"
              :disabled="!isCodeSent" 
            />
            <view
              class="code"
              @click="getCode"
              :class="{ 'disabled': !isPhoneValid || isDisabled }"
              :style="{
                color: isPhoneValid && !isDisabled ? '#1A195A' : '#ccc',
              }"
              >| {{ buttonText }}
            </view>
          </view>
        </view>
        <view class="ipt">
          <text style="color: aliceblue; padding-left: 32rpx">设置登录密码</text>
          <text class="error-tip" v-if="errors.loginPassword">{{ errors.loginPassword }}</text>
          <input
            type="password"
            placeholder="请输入8~12位密码"
            placeholder-style="color:#666"
            v-model="params.loginPassword"
            :maxlength="12"
          />
        </view>
        <view class="ipt">
          <text style="color: aliceblue; padding-left: 32rpx">确认登录密码</text>
          <text class="error-tip" v-if="errors.comfirmLoginPassword">{{ errors.comfirmLoginPassword }}</text>
          <input
            type="password"
            placeholder="请再次输入密码"
            placeholder-style="color:#666"
            v-model="params.comfirmLoginPassword"
            :maxlength="12"
          />
        </view>
        <view class="ipt">
          <text style="color: aliceblue; padding-left: 32rpx">设置支付密码</text>
          <text class="error-tip" v-if="errors.payPassword">{{ errors.payPassword }}</text>
          <input
            type="password"
            placeholder="请输入6位数字支付密码"
            placeholder-style="color:#666"
            v-model="params.payPassword"
            :maxlength="6"
          />
        </view>
        <view class="ipt">
          <text style="color: aliceblue; padding-left: 32rpx">确认支付密码</text>
          <text class="error-tip" v-if="errors.comfirmPayPassword">{{ errors.comfirmPayPassword }}</text>
          <input
            type="password"
            placeholder="请再次输入支付密码"
            placeholder-style="color:#666"
            v-model="params.comfirmPayPassword"
            :maxlength="6"
          />
        </view>
        <view class="ipt">
          <span style="color: aliceblue; padding-left: 32rpx">邀请码</span>
          <view class="invitation-container">
            <input
              type="text"
              placeholder="请输入邀请码"
              placeholder-style="color:#666"
              v-model="params.invitation"
              :maxlength="11"
            />
            <uni-icons
              type="scan"
              size="30"
              class="icon"
              color="blueviolet"
              @click="handleScan"
            ></uni-icons>
          </view>
        </view>

        <view class="agreement">
          <wd-checkbox
            v-model="agree"
            @toggle="handleSelected"
            checked-color="blue"
          />
          <text class="agree-text">我已阅读并接受《隐私政策》和《服务协议》</text>
        </view>
        <button class="login" @click="handleRegister">注册并登录</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import uniIcons from "@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue";
import { apiUserRegister, apiSendCode } from "@/api/login";
import { ref, computed } from "vue";

// 是否同意协议
const agree = ref(false);
const handleSelected = () => {
  agree.value = !agree.value;
};

// 表单数据
const params = ref({
  username: "",
  phone: "",
  security: "",
  loginPassword: "",
  comfirmLoginPassword: "",
  payPassword: "",
  comfirmPayPassword: "",
  invitation: "",
});

// 错误信息
const errors = ref({});

// 验证码按钮状态
const isDisabled = ref(false);
const isCodeSent = ref(false); // 控制验证码输入框是否可用
const buttonText = ref("获取验证码");

// ✅ 新增：记录验证码发送时间（用于判断是否过期）
let codeSentTime = null;

// 手机号合法性计算属性
const isPhoneValid = computed(() => {
  const phone = params.value.phone;
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phone && phoneRegex.test(phone);
});

// ✅ 校验验证码是否过期（60秒内有效）
const isCodeExpired = () => {
  if (!codeSentTime) return true;
  return Date.now() - codeSentTime > 60000; // 超过60秒
};

// 获取验证码
const getCode = async () => {
  if (!isPhoneValid.value || isDisabled.value) return;

  const res = await apiSendCode({ phone: params.value.phone });
  if (res.code !== 200) {
    uni.showToast({ title: res.message || "发送失败", icon: "none" });
    return;
  }

  // ✅ 验证码发送成功
  isCodeSent.value = true;
  codeSentTime = Date.now(); // 记录发送时间
  params.value.security = ""; // 清空上次输入
  uni.showToast({ title: "验证码已发送", icon: "none" });

  // 开始倒计时
  isDisabled.value = true;
  let count = 60;
  const timer = setInterval(() => {
    if (count > 0) {
      buttonText.value = `${count}秒重新获取`;
      count--;
    } else {
      clearInterval(timer);
      buttonText.value = "获取验证码";
      isDisabled.value = false;

    }
  }, 1000);
};

// 扫码
const handleScan = () => {
  uni.scanCode({
    success: (res) => {
      params.value.invitation = res.result;
    },
    fail: () => {
      uni.showToast({ title: "扫码失败", icon: "none" });
    }
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 表单验证逻辑（加强版）—— 禁止密码中任何位置出现空格
const validateForm = () => {
  errors.value = {};

  const username = params.value.username.trim();
  if (!username) {
    errors.value.username = "请输入用户名";
    return false;
  }

  if (username.length < 2) {
    errors.value.username = "用户名至少2个字符";
    return false;
  }

  if (username.length > 8) {
    errors.value.username = "用户名最多8个字符";
    return false;
  }

  if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(username)) {
    errors.value.username = "用户名不能包含特殊字符";
    return false;
  }

  if (!params.value.phone.trim()) {
    errors.value.phone = "请输入手机号码";
    return false;
  }

  if (!isPhoneValid.value) {
    errors.value.phone = "请输入正确的手机号码";
    return false;
  }

  const security = params.value.security.trim();
  if (!security) {
    errors.value.security = "请输入验证码";
    return false;
  }

  if (security.length < 4) {
    errors.value.security = "验证码长度不能小于4位";
    return false;
  }

  if (![4, 6].includes(security.length)) {
    errors.value.security = "验证码必须为4位或6位";
    return false;
  }

  if (!isCodeSent.value) {
    errors.value.security = "请先获取验证码";
    return false;
  }

  if (isCodeExpired()) {
    errors.value.security = "验证码已过期，请重新获取";
    return false;
  }

  const loginPwd = params.value.loginPassword;
  if (!loginPwd) {
    errors.value.loginPassword = "请设置登录密码";
    return false;
  }

  if (/\s/.test(loginPwd)) {
    errors.value.loginPassword = "密码不能包含空格";
    return false;
  }

  if (loginPwd.length < 8 || loginPwd.length > 12) {
    errors.value.loginPassword = "登录密码为8~12位";
    return false;
  }

  const confirmLoginPwd = params.value.comfirmLoginPassword;
  if (!confirmLoginPwd) {
    errors.value.comfirmLoginPassword = "请确认登录密码";
    return false;
  }

  if (/\s/.test(confirmLoginPwd)) {
    errors.value.comfirmLoginPassword = "密码不能包含空格";
    return false;
  }

  if (loginPwd !== confirmLoginPwd) {
    errors.value.comfirmLoginPassword = "两次输入密码不一致";
    return false;
  }

  const payPwd = params.value.payPassword;
  if (!payPwd) {
    errors.value.payPassword = "请设置支付密码";
    return false;
  }

  if (/\s/.test(payPwd)) {
    errors.value.payPassword = "支付密码不能包含空格";
    return false;
  }

  if (payPwd.length !== 6 || !/^\d{6}$/.test(payPwd)) {
    errors.value.payPassword = "支付密码必须为6位数字";
    return false;
  }

  const confirmPayPwd = params.value.comfirmPayPassword;
  if (!confirmPayPwd) {
    errors.value.comfirmPayPassword = "请确认支付密码";
    return false;
  }

  if (/\s/.test(confirmPayPwd)) {
    errors.value.comfirmPayPassword = "支付密码不能包含空格";
    return false;
  }

  if (payPwd !== confirmPayPwd) {
    errors.value.comfirmPayPassword = "两次输入密码不一致";
    return false;
  }

  return true;
};

// 注册处理
const handleRegister = async () => {
  if (!agree.value) {
    uni.showToast({
      title: "请勾选协议",
      icon: "none",
    });
    return;
  }

  if (!validateForm()) return;

  const resisterRes = await apiUserRegister({
    username: params.value.username.trim(),
    password: params.value.loginPassword.trim(),
    phone: params.value.phone,
    paymentPsw: params.value.payPassword.trim(),
    verificationCode: params.value.security,
    referralCode: params.value.invitation,
  });

  if (resisterRes.code === 200) {
    uni.showToast({
      title: "注册成功",
      icon: "none",
    });
    setTimeout(() => {
      uni.navigateTo({ url: "/subPackage/login/phoneLogin" });
    }, 500);
  } else {
    uni.showToast({
      title: resisterRes.message || "注册失败",
      icon: "none",
    });
  }
};
</script>

<style lang="scss" scoped>
/* 原有样式完全未做任何改动 */
.register {
  background-color: #9897fe;
  width: 100vw;
  height: 100vh;
  position: relative;
  .head {
    position: absolute;
    top: 30rpx;
    left: 40rpx;
    image {
      width: 100rpx;
      height: 100rpx;
    }
  }
  .content {
    overflow: scroll;
    position: absolute;
    top: 150rpx;
    width: 87%;
    left: 50rpx;
    height: 89%;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.15);
    background: #A0C0FE;
    border-radius: 40rpx;
    box-sizing: border-box;
    .title {
      text-align: center;
      padding: 20rpx 0;
      height: 80rpx;
      background-color: #d6d6ff;
      border-top-left-radius: 40rpx;
      border-top-right-radius: 40rpx;
      line-height: 80rpx;
      color: #1a195a;
      font-weight: 500;
    }

    .security {
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      input {
        margin-top: 10rpx;
        width: calc(100% - 350rpx);
        height: 80rpx;
        background-color: #fff;
        border-radius: 40rpx;
        padding-left: 50rpx;
        padding-right: 300rpx;
      }
      .code {
        position: absolute;
        left: 330rpx;
        top: 31rpx;
        right: 0;
      }
    }

    .invitation-container {
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      input {
        margin-top: 10rpx;
        width: calc(100% - 300rpx);
        height: 80rpx;
        background-color: #fff;
        border-radius: 40rpx;
        padding-left: 50rpx;
        padding-right: 250rpx;
      }
      .icon {
        position: absolute;
        left: 460rpx;
        top: 25rpx;
      }
    }

    .content-item {
      padding: 0 20rpx;

      .ipt {
        padding: 0 40rpx;
        margin-top: 20rpx;
        input {
          margin-top: 10rpx;
          width: calc(100% - 50rpx);
          height: 80rpx;
          background-color: #fff;
          border-radius: 40rpx;
          padding-left: 50rpx;
        }
        .error-tip {
          font-size: 24rpx;
          color: #e74c3c;
          margin-top: 8rpx;
          padding-left: 20rpx;
          height: 36rpx;
          line-height: 36rpx;
          margin-left: 40rpx;
        }
      }

      .agreement {
        display: flex;
        align-items: center;
        margin-bottom: 24rpx;
        margin-left: 40rpx;
        color: #1a195a;
        font-size: 25rpx;
        margin-top: 30rpx;
        .agree-text {
          margin-left: 10rpx;
        }
      }

      .login {
        margin-top: 20rpx;
        margin-bottom: 40rpx;
        background-color: #5756b3;
        color: #fff;
        border-radius: 40rpx;
        height: 90rpx;
        width: 500rpx;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>